﻿using System.Text.Json;

namespace P9_WeatherAPI;

public class WeatherService
{
    private readonly string _apiKey = "b9e11ac7dd42692301af32d3cce33f57";
    private readonly string _apiUrl= "http://api.openweathermap.org/data/2.5/weather";
    private readonly HttpClient _httpClient;

    public WeatherService()
    {
        _httpClient=new HttpClient();
    }

    public async Task<WeatherData> GetWeatherAsync(string city)
    {
        string requestUrl = $"{_apiUrl}?q={city}&appid={_apiKey}&units=metric&lang=zh_cn"; // 添加单位和语言参数
        try
        {
            HttpResponseMessage response = await _httpClient.GetAsync(requestUrl);
            response.EnsureSuccessStatusCode(); // 抛出异常如果状态码不是成功

            string jsonString = await response.Content.ReadAsStringAsync();
            WeatherData weatherData = JsonSerializer.Deserialize<WeatherData>(jsonString);
            return weatherData;
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"API 请求错误: {ex.Message}");
            return null;
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"JSON 解析错误: {ex.Message}");
            return null;
        }
    }
    
}